package com.circle.rest.modular.nt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.circle.rest.core.common.enums.NtHistoryStatus;
import com.circle.rest.core.manager.webScoket.WebSocketServer;
import com.circle.rest.modular.nt.dao.HistoryMapper;
import com.circle.rest.modular.nt.dao.InboxMapper;
import com.circle.rest.modular.nt.model.History;
import com.circle.rest.modular.nt.model.Inbox;
import com.circle.rest.modular.nt.service.IHistoryService;
import com.circle.rest.modular.sys.dao.UserMapper;
import com.circle.rest.modular.sys.model.User;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 通知历史 服务实现类
 * </p>
 *
 * @author 赵航
 * @since 2019-04-09
 */
@Service
public class HistoryServiceImpl extends ServiceImpl<HistoryMapper, History> implements IHistoryService {

    @Resource
    private InboxMapper inboxMapper;

    @Resource
    private UserMapper userMapper;

    /**
     * 撤销通知
     *
     * @param id
     * @return
     */
    @Override
    @Transactional
    public boolean revoke(String id) {
        //history撤销
        History history = this.baseMapper.selectById(id);
        history.setStatus(NtHistoryStatus.REVOKE.getCode());
        history.setUpdateTime(LocalDateTime.now());
        this.baseMapper.updateById(history);

        //inbox删除
        QueryWrapper<Inbox> wrapper = new QueryWrapper<>();
        wrapper.eq("history_id", history.getId());
        inboxMapper.delete(wrapper);

        return true;
    }

    /**
     * 发送通知
     * 异步处理
     *
     * @param history
     */
    @Async
    @Override
    @Transactional
    public void send(History history) throws IOException {
        List<User> users = userMapper.selectNotifyUsers(history.getDept(), history.getRole(), history.getInclude(), history.getNotInclude());
        for (User user : users) {
            Inbox inbox = new Inbox();
            inbox.setHistoryId(history.getId());
            inbox.setContentId(history.getContentId());
            inbox.setUserId(user.getId());
            inboxMapper.insert(inbox);
        }
        String userIds = users.stream().map(User::getId).collect(Collectors.joining(","));
        //TODO 发送消息通知
        WebSocketServer.sendInfo("您有一条新的消息", userIds);
        History update = this.baseMapper.selectById(history.getId());
        update.setStatus(NtHistoryStatus.SENT.getCode());
        update.setUpdateTime(LocalDateTime.now());
        this.baseMapper.updateById(update);
    }
}
